package org.jeecg.modules.clue.controller;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.clue.entity.InvestmentPromotionClue;
import org.jeecg.modules.clue.service.IInvestmentPromotionClueService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.service.ISysDictService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 招商线索表
 * @Author: jeecg-boot
 * @Date:   2022-01-27
 * @Version: V1.0
 */
@Api(tags="招商线索表")
@RestController
@RequestMapping("/org.jeecg.modules.clue/investmentPromotionClue")
@Slf4j
public class InvestmentPromotionClueController extends JeecgController<InvestmentPromotionClue, IInvestmentPromotionClueService> {
	@Autowired
	private IInvestmentPromotionClueService investmentPromotionClueService;
	 @Value("${jeecg.path.upload}")
	 private String upLoadPath;
	 @Autowired
	 private ISysDictService sysDictService;
	
	/**
	 * 分页列表查询
	 *
	 * @param investmentPromotionClue
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "招商线索表-分页列表查询")
	@ApiOperation(value="招商线索表-分页列表查询", notes="招商线索表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(InvestmentPromotionClue investmentPromotionClue,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<InvestmentPromotionClue> queryWrapper = QueryGenerator.initQueryWrapper(investmentPromotionClue, req.getParameterMap());
		Page<InvestmentPromotionClue> page = new Page<InvestmentPromotionClue>(pageNo, pageSize);
		IPage<InvestmentPromotionClue> pageList = investmentPromotionClueService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param investmentPromotionClue
	 * @return
	 */
	@AutoLog(value = "招商线索表-添加")
	@ApiOperation(value="招商线索表-添加", notes="招商线索表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody InvestmentPromotionClue investmentPromotionClue) {
		investmentPromotionClueService.save(investmentPromotionClue);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param investmentPromotionClue
	 * @return
	 */
	@AutoLog(value = "招商线索表-编辑")
	@ApiOperation(value="招商线索表-编辑", notes="招商线索表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody InvestmentPromotionClue investmentPromotionClue) {
		investmentPromotionClueService.updateById(investmentPromotionClue);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "招商线索表-通过id删除")
	@ApiOperation(value="招商线索表-通过id删除", notes="招商线索表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		investmentPromotionClueService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "招商线索表-批量删除")
	@ApiOperation(value="招商线索表-批量删除", notes="招商线索表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.investmentPromotionClueService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "招商线索表-通过id查询")
	@ApiOperation(value="招商线索表-通过id查询", notes="招商线索表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		InvestmentPromotionClue investmentPromotionClue = investmentPromotionClueService.getById(id);
		if(investmentPromotionClue==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(investmentPromotionClue);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param investmentPromotionClue
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, InvestmentPromotionClue investmentPromotionClue) {
        return exportInvestmentPromotionClueXls(request, investmentPromotionClue, InvestmentPromotionClue.class, "招商线索表");
    }

	 /**
	  * 导出excel
	  *
	  * @param request
	  */
	 protected ModelAndView exportInvestmentPromotionClueXls(HttpServletRequest request, InvestmentPromotionClue object, Class<InvestmentPromotionClue> clazz, String title) {
		 // Step.1 组装查询条件
		 QueryWrapper<InvestmentPromotionClue> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<InvestmentPromotionClue> pageList = service.list(queryWrapper);
		 for(int i=0;i<pageList.size();i++){
			 InvestmentPromotionClue invClue = pageList.get(i);
			 Field[] field = invClue.getClass().getDeclaredFields(); // 获取实体类的所有属性，返回Field数组
			 for (int j = 0; j < field.length; j++) {
				 List<DictModel> ls = sysDictService.getDictItems(investmentPromotionClueService.convertCamelCase(field[j].getName()));
				 if(ls.size() > 0){
					 for(int k=0;k<ls.size();k++){
						 DictModel dictModel = ls.get(k);
						 try {
						 	Method m1 = invClue.getClass().getMethod("get"+field[j].getName().substring(0,1).toUpperCase() + field[j].getName().substring(1));
							String o = (String)m1.invoke(invClue);
							if(o != null){
								if(o.equals(dictModel.getValue())){
									Method m2 = invClue.getClass().getMethod("set"+field[j].getName().substring(0,1).toUpperCase() + field[j].getName().substring(1),String.class);
									m2.invoke(invClue,dictModel.getTitle());
								}
							}
						 } catch (NoSuchMethodException e) {
							 e.printStackTrace();
						 } catch (IllegalAccessException e) {
							 e.printStackTrace();
						 } catch (InvocationTargetException e) {
							 e.printStackTrace();
						 }
					 }
				 }
			 }
		 }
		 List<InvestmentPromotionClue> exportList = pageList;

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, clazz);
		 //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
		 ExportParams  exportParams=new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
		 exportParams.setImageBasePath(upLoadPath);
		 //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
		 mv.addObject(NormalExcelConstants.PARAMS,exportParams);
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
	 }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return importInvestmentPromotionClueExcel(request, response, InvestmentPromotionClue.class);
    }

	 /**
	  * 通过excel导入数据
	  *
	  * @param request
	  * @param response
	  * @return
	  */
	 protected Result<?> importInvestmentPromotionClueExcel(HttpServletRequest request, HttpServletResponse response, Class<InvestmentPromotionClue> clazz) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<InvestmentPromotionClue> list = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);

				 for(int i=0;i<list.size();i++){
					 InvestmentPromotionClue invClue = list.get(i);
					 Field[] field = invClue.getClass().getDeclaredFields(); // 获取实体类的所有属性，返回Field数组
					 for (int j = 0; j < field.length; j++) {
						 List<DictModel> ls = sysDictService.getDictItems(investmentPromotionClueService.convertCamelCase(field[j].getName()));
						 if(ls.size() > 0){
							 for(int k=0;k<ls.size();k++){
								 DictModel dictModel = ls.get(k);
								 try {
									 Method m1 = invClue.getClass().getMethod("get"+field[j].getName().substring(0,1).toUpperCase() + field[j].getName().substring(1));
									 String o = (String)m1.invoke(invClue);
									 if(o != null){
                                         if(o.equals(dictModel.getTitle())){
                                             Method m2 = invClue.getClass().getMethod("set"+field[j].getName().substring(0,1).toUpperCase() + field[j].getName().substring(1),String.class);
                                             m2.invoke(invClue,dictModel.getValue());
                                         }
                                     }
								 } catch (NoSuchMethodException e) {
									 e.printStackTrace();
								 } catch (IllegalAccessException e) {
									 e.printStackTrace();
								 } catch (InvocationTargetException e) {
									 e.printStackTrace();
								 }
							 }
						 }
					 }
				 }
				 //update-begin-author:taoyan date:20190528 for:批量插入数据
				 long start = System.currentTimeMillis();
				 service.saveBatch(list);
				 //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
				 //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 //update-end-author:taoyan date:20190528 for:批量插入数据
				 return Result.ok("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
	 }

}
